package JaggSoft;

import JaggSoft.Utilidades.*;
import java.awt.*;
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.TableRowSorter;

public class Usuarios extends javax.swing.JInternalFrame {
    private boolean nuevo;
    private String codigo="";
    private String id_bitacora;
    private JFileChooser selector;
    public Usuarios() {
        initComponents();
        this.setLocation(new Point(70,0));
        selector=new JFileChooser();
        selector.setFileFilter(new FileNameExtensionFilter("Libro de Excel",new String[]{"xls","xlsx"}));
        selector.setMultiSelectionEnabled(false);
        selector.setSelectedFile(new File("usuarios.xls"));
        CargarTipoUsuarios();
        CargarUsuarios();
        BloquearControles(true);
        BloquearTexto(true);
        Limpiar();
        if(Conexion.bitacora) id_bitacora=Util.IniciarBitacora(this.getTitle());
    }
    private void CargarTipoUsuarios(){
        jcbTipoUsuario.removeAllItems();
        String[] columnas={"id","descripcion"};
        Util.CargarJComboBox(jcbTipoUsuario,"SELECT id_tipo,descripcion FROM tipousuario;",columnas);
        
    }
    private void CargarUsuarios(){
        Util.CargarTabla(jtblUsuarios,"SELECT u.id_usuario,u.nombre,u.apellido,u.identidad,u.id_tipo,tp.descripcion,u.usuario FROM usuario u INNER JOIN tipousuario tp ON u.id_tipo=tp.id_tipo WHERE u.id_usuario!="+Conexion.ID+";",new String []{"ID","Nombres","Apellidos","N° de Identidad","id_tipo","Tipo","Usuario"});
        Util.OcultarColumna(jtblUsuarios,0);
        Util.OcultarColumna(jtblUsuarios,4);
        Util.AlinearColumnas(jtblUsuarios,SwingConstants.CENTER);
        jtblUsuarios.setRowSorter(new TableRowSorter<MyModeloTabla>((MyModeloTabla) jtblUsuarios.getModel()));
    }
    private void BloquearControles(boolean estado){
        jbtnNuevo.setEnabled(estado);
        jbtnGuardar.setEnabled(!estado);
        jbtnModificar.setEnabled(estado);
        jbtnEliminar.setEnabled(estado);
        jbtnCancelar.setEnabled(!estado);
    }
    private void BloquearTexto(boolean estado){
        jtfNombres.setEditable(!estado);
        jtfApellidos.setEditable(!estado);
        jtfIdentidad.setEditable(!estado);
        jtfUsuario.setEditable(!estado);
        jpfPassword.setEditable(!estado);
        jcbTipoUsuario.setEnabled(!estado);
    }
    private void Limpiar(){
        jtfNombres.setText(null);
        jtfApellidos.setText(null);
        jtfIdentidad.setText(null);
        jtfUsuario.setText(null);
        jpfPassword.setText(null);
        jcbTipoUsuario.setSelectedIndex(-1);
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        jtfNombres = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jtfApellidos = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jcbTipoUsuario = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jtfIdentidad = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jtfUsuario = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jpfPassword = new javax.swing.JPasswordField();
        jPanel2 = new javax.swing.JPanel();
        jbtnCancelar = new javax.swing.JButton();
        jbtnEliminar = new javax.swing.JButton();
        jbtnModificar = new javax.swing.JButton();
        jbtnGuardar = new javax.swing.JButton();
        jbtnNuevo = new javax.swing.JButton();
        jbtnExportar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtblUsuarios = new javax.swing.JTable();

        setClosable(true);
        setMaximizable(true);
        setTitle("Administración de Usuarios");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/usuarios.png"))); // NOI18N
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentMoved(java.awt.event.ComponentEvent evt) {
                formComponentMoved(evt);
            }
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        jLabel7.setText("Nombres:");

        jLabel2.setText("Apellidos");

        jLabel4.setText("Tipo de Usario:");

        jLabel3.setText("Número de Identidad:");

        jtfIdentidad.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jtfIdentidadKeyTyped(evt);
            }
        });

        jLabel5.setText("Usuario");

        jLabel6.setText("Contraseña:");

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Acciones"));

        jbtnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_cancelar.png"))); // NOI18N
        jbtnCancelar.setToolTipText("Cancelar");
        jbtnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnCancelarActionPerformed(evt);
            }
        });

        jbtnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_eliminar.png"))); // NOI18N
        jbtnEliminar.setToolTipText("Eliminar");
        jbtnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnEliminarActionPerformed(evt);
            }
        });

        jbtnModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_modificar.png"))); // NOI18N
        jbtnModificar.setToolTipText("Modificar");
        jbtnModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnModificarActionPerformed(evt);
            }
        });

        jbtnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_guardar.png"))); // NOI18N
        jbtnGuardar.setToolTipText("Guardar");
        jbtnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnGuardarActionPerformed(evt);
            }
        });

        jbtnNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_nuevo.png"))); // NOI18N
        jbtnNuevo.setToolTipText("Nuevo");
        jbtnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnNuevoActionPerformed(evt);
            }
        });

        jbtnExportar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/excel.png"))); // NOI18N
        jbtnExportar.setToolTipText("Exportar a Excel");
        jbtnExportar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnExportarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addComponent(jbtnNuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jbtnNuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jbtnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jbtnModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jbtnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jbtnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jbtnExportar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        jtblUsuarios.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtblUsuariosMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jtblUsuarios);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jtfUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jtfNombres, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtfIdentidad, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 52, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jcbTipoUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGap(18, 18, 18)
                                        .addComponent(jLabel2))
                                    .addComponent(jLabel6))
                                .addGap(15, 15, 15)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jtfApellidos)
                                    .addComponent(jpfPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addContainerGap())
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(142, 142, 142)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jcbTipoUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jtfIdentidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(jtfNombres, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(jtfApellidos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jtfUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(jpfPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void jbtnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnCancelarActionPerformed
        BloquearControles(true);
        BloquearTexto(true);
        if(codigo.equals(""))
            Limpiar();
    }//GEN-LAST:event_jbtnCancelarActionPerformed
    private void jbtnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnEliminarActionPerformed
        if(!codigo.equals("")){
            if(JOptionPane.showConfirmDialog(null,"¿Esta seguro de eliminar el usuario: "+GetUsuario()+" y todos lo que este realacionado con el usuario?","Eliminar Usuario", JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
                if(Conexion.EjecutarProcedimientoAlmacenado("CALL EliminarUsuario("+codigo+")")){
                    if(Conexion.bitacora) Util.AccionBitacora(id_bitacora,"Eliminar Usuario: "+Util.ComponerTexto(jtfNombres.getText()+" "+jtfApellidos.getText()));
                    CargarUsuarios();
                    JOptionPane.showMessageDialog(null,"¡Usuario Eliminado!","Usuario",JOptionPane.INFORMATION_MESSAGE);
                }
                else
                    JOptionPane.showMessageDialog(null,"¡Hubo un error al eliminar el usuario!","Usuario",JOptionPane.ERROR_MESSAGE);
            }
        }
        else
            JOptionPane.showMessageDialog(null,"Para eliminar un usuario primero debe seleccionar un usuario de la tabla","No ha seleccionado usuario",JOptionPane.WARNING_MESSAGE);
        Limpiar();
    }//GEN-LAST:event_jbtnEliminarActionPerformed
    private String GetUsuario(){
        for(int i=0;i<jtblUsuarios.getRowCount();i++)
            if(jtblUsuarios.getValueAt(i,0).toString().equals(codigo))
                return jtblUsuarios.getValueAt(i,1).toString()+" "+jtblUsuarios.getValueAt(i,2).toString();
        return "";
    }
    private void jbtnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnModificarActionPerformed
        BloquearControles(false);
        BloquearTexto(false);
        nuevo=false;
    }//GEN-LAST:event_jbtnModificarActionPerformed
    private void jbtnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnGuardarActionPerformed
        if(ValidarCampos()){
            if(nuevo){
                Guardar();
                BloquearControles(true);
                BloquearTexto(true);
                Limpiar();
                CargarUsuarios();
            }
            else{
                if(!codigo.equals("")){
                    Actualizar();
                    CargarUsuarios();
                    BloquearControles(true);
                    BloquearTexto(true);
                }
                else
                    JOptionPane.showMessageDialog(null,"Para actualizar la información de un usuario primero debe seleccionar un usuario de la tabla","No ha seleccionado usuario",JOptionPane.WARNING_MESSAGE);
            }
        }
    }//GEN-LAST:event_jbtnGuardarActionPerformed
    private boolean ValidarCampos(){
        String msj=null;
        msj=(!jtfIdentidad.getText().equals("")?(ContarNumeros(jtfIdentidad.getText())!=13?"El número de identidad debe contener 13 digitos.":""):"Falta ingresar el número de identidad");
        msj+=(jcbTipoUsuario.getSelectedIndex()>-1?"":(!msj.equals("")?", seleccionar el tipo de usuario":"Falta seleccionar el tipo de usuario"));
        msj+=(jtfNombres.getText().equals("")?(!msj.equals("")?", el(los) nombre(s)":"Falta ingresar el(los) nombre(s)"):"");
        msj+=(jtfApellidos.getText().equals("")?(!msj.equals("")?", el(los) apellido(s)":"Falta ingresar el(los) apellido(s)"):"");
        msj+=(jtfUsuario.getText().equals("")?(!msj.equals("")?", el usuario":"Falta ingresar el usuario"):"");
        msj+=(jpfPassword.getText().equals("")?(!msj.equals("")?", la contraseña":"Falta ingresar la contraseña"):"");
        if(!msj.equals("")) JOptionPane.showMessageDialog(null,msj+".","Falta ingresar algunos campos",JOptionPane.WARNING_MESSAGE);
        return msj.equals("");
    }
    private void Guardar(){
        if(Conexion.EjecutarProcedimientoAlmacenado("CALL AgregarUsuario('"+Util.ComponerTexto(jtfNombres.getText())+"','"
                +Util.ComponerTexto(jtfApellidos.getText())+"','"+GetIdentidadFormateada(jtfIdentidad.getText())+"',"
                +((ModeloItemValor)jcbTipoUsuario.getSelectedItem()).getValor()+",'"+Util.ComponerTexto(jtfUsuario.getText())+"','"
                +Util.ComponerTexto(jpfPassword.getText())+"');")){
                    if(Conexion.bitacora) Util.AccionBitacora(id_bitacora,"Guardar Usuario: "+Util.ComponerTexto(jtfNombres.getText()+" "+jtfApellidos.getText()));
                    CargarUsuarios();
                    JOptionPane.showMessageDialog(null,"¡Usuario Agregado!","Usuario",JOptionPane.INFORMATION_MESSAGE);
        }
        else
            JOptionPane.showMessageDialog(null,"¡Hubo un error al agregar el usuario!","Usuario",JOptionPane.ERROR_MESSAGE);
    }
    private void Actualizar(){
        if(Conexion.EjecutarProcedimientoAlmacenado("CALL ModificarUsuario("+codigo+",'"+Util.ComponerTexto(jtfNombres.getText())+"','"
                +Util.ComponerTexto(jtfApellidos.getText())+"','"+GetIdentidadFormateada(jtfIdentidad.getText())+"',"
                +((ModeloItemValor)jcbTipoUsuario.getSelectedItem()).getValor()+",'"+Util.ComponerTexto(jtfUsuario.getText())+"','"
                +Util.ComponerTexto(jpfPassword.getText())+"')")){
                    if(Conexion.bitacora) Util.AccionBitacora(id_bitacora,"Modificar Usuario: "+Util.ComponerTexto(jtfNombres.getText()+" "+jtfApellidos.getText()));
                    JOptionPane.showMessageDialog(null,"¡Usuario Modificado!","Usuario",JOptionPane.INFORMATION_MESSAGE);
        }
        else
            JOptionPane.showMessageDialog(null,"¡Hubo un error al modificar el usuario!","Usuario",JOptionPane.ERROR_MESSAGE);
    }
    private String GetIdentidadFormateada(String identidad){
        identidad=identidad.replace("-","");
        return identidad.substring(0,4)+"-"+identidad.substring(4,8)+"-"+identidad.substring(8);
    }
    private void jbtnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnNuevoActionPerformed
        BloquearControles(false);
        BloquearTexto(false);
        Limpiar();
        nuevo=true;
    }//GEN-LAST:event_jbtnNuevoActionPerformed
    private void jtfIdentidadKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfIdentidadKeyTyped
        String dato=(jtfIdentidad.getText()+evt.getKeyChar()).replaceAll("-","");
        if(!Util.esNumero(dato,false))
            evt.consume();
        if(ContarNumeros(dato)>13)
            evt.consume();
    }//GEN-LAST:event_jtfIdentidadKeyTyped
    private void jtblUsuariosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtblUsuariosMouseClicked
        if(jtblUsuarios.getSelectedRow()>-1)
            CargarUsuario(jtblUsuarios.getSelectedRow());
        else
            evt.consume();
    }//GEN-LAST:event_jtblUsuariosMouseClicked

    private void formComponentMoved(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentMoved
        if(evt.getComponent().getLocation().x<70)
            evt.getComponent().setLocation(70,evt.getComponent().getLocation().y);
        if(evt.getComponent().getLocation().y<0)
            evt.getComponent().setLocation(evt.getComponent().getLocation().x,0);
    }//GEN-LAST:event_formComponentMoved
    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        if(this.getParent().getWidth()-70<this.getWidth()  && this.isMaximum)
            this.setSize(this.getWidth()-70,this.getHeight());
    }//GEN-LAST:event_formComponentResized
    private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
        if(Conexion.bitacora) Util.ClausurarBitacora(id_bitacora);
    }//GEN-LAST:event_formInternalFrameClosing

    private void jbtnExportarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnExportarActionPerformed
        if(jtblUsuarios.getRowCount()>0){
            if(selector.showSaveDialog(null)==JOptionPane.OK_OPTION){
                try {
                    String ruta=selector.getSelectedFile().getAbsolutePath();
                    if(!ruta.endsWith(".xls"))
                        ruta+=".xls";
                    File archivo_excel=new File(ruta);
                    switch(Util.ExportarExcel(jtblUsuarios,archivo_excel,"Usuarios")){
                        case OK:
                        JOptionPane.showMessageDialog(null,"Archivo Exportado",this.getTitle(),JOptionPane.INFORMATION_MESSAGE);
                        Desktop.getDesktop().open(archivo_excel);
                        break;
                        case CANCELADO:
                        break;
                        case ERROR:
                        JOptionPane.showMessageDialog(null,"No se pudo exportar el archivo","Error",JOptionPane.ERROR_MESSAGE);
                        break;
                    }
                } catch (Exception ex) {System.err.println(ex.getMessage());}
            }
        }
        else
            JOptionPane.showMessageDialog(null,"No hay datos para exportar","Sin Datos",JOptionPane.WARNING_MESSAGE);
    }//GEN-LAST:event_jbtnExportarActionPerformed
    private void CargarUsuario(int fila){
        String tipo=jtblUsuarios.getValueAt(fila,4).toString();
        this.codigo=jtblUsuarios.getValueAt(fila,0).toString();
        jtfNombres.setText(jtblUsuarios.getValueAt(fila,1).toString());
        jtfApellidos.setText(jtblUsuarios.getValueAt(fila,2).toString());
        jtfIdentidad.setText(jtblUsuarios.getValueAt(fila,3).toString());
        for(int i=0;i<jcbTipoUsuario.getItemCount();i++){
            if(((ModeloItemValor)jcbTipoUsuario.getItemAt(i)).getValor().equals(tipo)){
                jcbTipoUsuario.setSelectedIndex(i);
                break;
            }
        }
        jtfUsuario.setText(jtblUsuarios.getValueAt(fila,6).toString());
        jpfPassword.setText("");
    }
    private int ContarNumeros(String texto){
        int n=0;
        for(char c:texto.toCharArray())
            if("0123456789".contains(""+c))
                n++;
        return n;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbtnCancelar;
    private javax.swing.JButton jbtnEliminar;
    private javax.swing.JButton jbtnExportar;
    private javax.swing.JButton jbtnGuardar;
    private javax.swing.JButton jbtnModificar;
    private javax.swing.JButton jbtnNuevo;
    private javax.swing.JComboBox jcbTipoUsuario;
    private javax.swing.JPasswordField jpfPassword;
    private javax.swing.JTable jtblUsuarios;
    private javax.swing.JTextField jtfApellidos;
    private javax.swing.JTextField jtfIdentidad;
    private javax.swing.JTextField jtfNombres;
    private javax.swing.JTextField jtfUsuario;
    // End of variables declaration//GEN-END:variables
}